#!/usr/bin/env bash
set -eEu
set -o pipefail

################################################################################
# Run the test harness.
# Invoke from the root of the git repo as "ci/test".
################################################################################

. ci/bootstrap

main() {
  if [[ "${DEBUG:-unset}" == 'unset' ]]; then
    # Without `--verbose', pre-commit only shows output when status != 0.
    verbose=''
  else
    # With `--verbose', pre-commit shows output regardless of exit status.
    verbose='--verbose'
  fi

  run_precommit
  try_precommit

  # pre-commit does not have a CLI option to exclude files (ci/ansi),
  # so do this one separate from the rest.
  declare -a files
  while IFS= read -r line; do
    files=("${files[@]}" "${line}")
  done < <(git ls-files | grep -vE '^ci/ansi$')
  run pre-commit try-repo "$(pwd)" require-ascii --verbose --files "${files[@]}"
}

run_precommit() {
  info 'Run pre-commit against all files'
  run pre-commit run --all-files "${verbose}" --hook-stage manual
}

try_precommit() {
  info 'Try local hooks'
  checks='
    bundler-audit
    fasterer
    markdownlint
    protect-first-parent
    reek
    rubocop
    script-must-have-extension
    script-must-not-have-extension
    shfmt
  '
  for check in ${checks}; do
    run pre-commit try-repo ./ "${check}" --all-files --verbose
  done
}

main
